import path from "path/posix";
import fs from "fs";
import { getOptions } from "./options";
export enum FILETYPE {
  dir = "dir",
  file = "file",
  index = "index",
  unknown = "unknown",
}
export enum ACTIONTYPE {
  main = "main",
  createdTranslate = "createdTranslate",
  awaitCollect = "awaitCollect",
  lazyTransForm = "lazyTransForm",
  done = "done",
}

type Targets = { [p: string]: string }[] | null;

export interface Node {
  fileName: string;
  fileType: FILETYPE;
  done: boolean;
  apiTime?: number;
  fileTime?: number;
  ignoreKey?: string[]; //忽略的key
  targets?: Targets;
  outerPath: string;
  importPath: string;
  allTime?: number;
  msg?: string;
  children?: Node[];
}
const { suffix, lazy, rootPath } = getOptions();

export interface GenNodeParam {
  importPath: string;
  outerPath: string;
  fileList: string[];
  targets?: Targets;
}
export const genNode = (param: GenNodeParam) => {
  const { importPath, outerPath, targets, fileList } = param;
  return fileList.map((fileName) => {
    let children: undefined | Node[];
    let fileType: FILETYPE;

    let childTargets: Targets = null;
    if (targets) {
      childTargets = targets.map((item) => {
        const key = Object.keys(item)[0];
        return {
          [path.join(key, fileName)]: item[key],
        };
      });
    }

    //根据后缀名来决定文件类型
    if (path.extname(fileName) === (suffix || ".ts")) {
      if (fileName.split(".")[0] === "index") {
        fileType = FILETYPE.index;
      } else {
        fileType = FILETYPE.file;
      }
    } else if (!path.extname(fileName)) {
      //走到这里一步就步就可以确认是文件夹了

      let dirName = fileName;
      fileType = FILETYPE.dir;
      const fileList = fs.readdirSync(importPath + "/" + dirName);

      //递归
      children = genNode({
        importPath: path.join(importPath, dirName),
        outerPath: path.join(outerPath, dirName),
        fileList,
        targets: childTargets,
      });
    } else {
      fileType = FILETYPE.unknown;
    }

    //填写初始值
    const node: Node = {
      fileName,
      importPath: path.join(importPath, fileName),
      fileType,
      targets: childTargets,
      outerPath: path.join(outerPath, fileName),
      done: false,
      children,
    };
    return node;
  });
};
